package cn.fanyamin.util.reflect;


import java.lang.reflect.Method;
/**
 * @author walter
 *
 */
public class ReflectMethod  {
	

	private String className;
	private String methodName;
	private Object[] parameters;
	
	private Object sqlObj;
	private Method sqlMethod;
	
	public ReflectMethod() {
		
	}
	public ReflectMethod(String className, String methodName, Object para)  {
		this(className, methodName, new Object[]{para});
	}
	
	public ReflectMethod(String className, String methodName, Object[] paras)  {
		this.className = className;
		this.methodName = methodName;
		this.parameters = paras;
		createObjectByName(className);		
		createMethodByName(methodName);
	}


	public ReflectMethod(Object obj, String methodName, Object[] paras)  {
		this.sqlObj = obj;
		this.className = obj.getClass().getName();
		this.methodName = methodName;
		this.parameters = paras;
		
		createMethodByName(methodName);
	}
	//TODO: get object from beanfactory
	private void createObjectByName(String className) {
		try {
			this.sqlObj = Class.forName(className);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
	}
	
	private void createMethodByName(String methodName)  {
		Class[] types = null;
		if (null != parameters && parameters.length > 0) {
			types = new Class[parameters.length];
			for (int i = 0; i < parameters.length; i++) {
				types[i] = parameters[i].getClass();
			}
		}

		try {
			sqlMethod = sqlObj.getClass().getDeclaredMethod(methodName, types);
		} catch (SecurityException e) {
			throw new RuntimeException(e);
		} catch (NoSuchMethodException e) {
			throw new RuntimeException(e);
		}
	}
	
	public String getClassName() {
		return className;
	}

	public void setClassName(String className) {
		this.className = className;
	}

	public String getMethodName() {
		return methodName;
	}

	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}

	public Object[] getParameters() {
		return parameters;
	}

	public void setParameters(Object[] parameters) {
		this.parameters = parameters;
	}

	public Object invoke() throws Exception {				
		return this.sqlMethod.invoke(this.sqlObj, this.parameters);
	}

	
	
}
